package com.huluobo.a2204parkdemo.patrol

import android.app.AlertDialog
import android.app.TimePickerDialog
import android.content.DialogInterface
import android.content.DialogInterface.OnClickListener
import android.os.Bundle
import android.util.Log
import android.widget.EditText
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2204parkdemo.R
import com.huluobo.a2204parkdemo.adapter.PointAdapter
import com.huluobo.a2204parkdemo.databinding.ActivityAddPatrolBinding
import com.huluobo.base.bean.PPointBean
import com.huluobo.base.bean.PPointBeanItem
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.StringBuilder
import java.util.Calendar

@AndroidEntryPoint
class AddPatrolActivity : BaseActivity<ActivityAddPatrolBinding, PatrolViewModel>() {
    private lateinit var pointAdapter: PointAdapter

    var startTime = 0L
    var endTime = 0L
    var time = 0L

    //上传新巡逻路线的参数
    private var pEnd = ""
    private var pStart = ""
    private var pTime = ""
    private var pPoints = ""
    private val newPointList = mutableListOf<PPointBeanItem>()


    val calendar = Calendar.getInstance().apply {
        set(Calendar.HOUR, 0)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }

    override fun initData() {
        viewModel.getAllPoint()
        viewModel.getAllPointSuccess.observe(this) {
            val list = Gson().fromJson(it, PPointBean::class.java)
            pointAdapter.data.clear()
            pointAdapter.data.addAll(list)
            pointAdapter.notifyDataSetChanged()
        }

        viewModel.addPointSuccess.observe(this) {
            ToastUtils.showLong("添加巡逻点成功")
            viewModel.getAllPoint()
        }

        viewModel.addPatrolSuccess.observe(this) {
            ToastUtils.showLong("添加巡逻路线成功")
            finish()
        }
    }

    override fun initView() {
        binding.addPatrolHeader.headerTitle.text = "添加巡更路线"
        binding.addPatrolHeader.headerBack.setOnClickListener { finish() }

        binding.addPatrolStartTimeIv.setOnClickListener {
            TimePickerDialog(
                this,
                { view, hourOfDay, minute ->
                    //把时间转换为Long,这样才能2个时间相减
                    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                    calendar.set(Calendar.MINUTE, minute)
                    startTime = calendar.timeInMillis
                    Log.i("TagA", "startTime:$startTime")
                    binding.addPatrolStartTimeNowTv.text = "$hourOfDay:$minute"
                },
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true
            ).show()
        }

        binding.addPatrolEndTimeIv.setOnClickListener {
            TimePickerDialog(
                this,
                { view, hourOfDay, minute ->
                    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                    calendar.set(Calendar.MINUTE, minute)
                    endTime = calendar.timeInMillis
                    Log.i("TagA", "endTime:$endTime")
                    binding.addPatrolEndTimeNowTv.text = "$hourOfDay:$minute"
                    time = endTime - startTime
                    if (time <= 0) {
                        ToastUtils.showLong("请重新选择时间")
                    } else {
                        val newTime = time / 1000 / 60 / 60
                        binding.addPatrolTimeNowTv.text = "${newTime}小时"
                    }
                },
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true
            ).show()
        }

        binding.addPatrolRv.layoutManager = GridLayoutManager(this, 2)
        pointAdapter = PointAdapter()
        binding.addPatrolRv.adapter = pointAdapter

        val pointListLiveData = MutableLiveData<List<PPointBeanItem>>()
        pointAdapter.setOnItemClickListener { adapter, view, position ->
            val pPointBeanItem =
                PPointBeanItem(pointAdapter.data[position].pointId, pointAdapter.data[position].pointName)
            newPointList.add(pPointBeanItem)
            pointListLiveData.postValue(newPointList)
        }

        pointListLiveData.observe(this) {
            val points = StringBuilder()
            newPointList.forEach {
                points.append(it.pointName)
                points.append(",")
            }
            binding.addPatrolChoicePointResultTv.text = points.toString()
        }

        binding.addPatrolAddPointBtn.setOnClickListener {
            val dialogView = layoutInflater.inflate(R.layout.dialog_add_point, null)
            AlertDialog.Builder(this)
                .setView(dialogView)
                .setTitle("添加巡逻点")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定") { dialog, which ->
                    val editText = dialogView.findViewById<EditText>(R.id.dialog_add_point_et)
                    val map = mutableMapOf<String, String>()
                    if (!editText.text.isNullOrEmpty()) {
                        map[Const.PARAM_ADD_POINT] = editText.text.toString()
                        val json = Gson().toJson(map)
                        val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                        viewModel.addPoint(body)
                    } else {
                        ToastUtils.showLong("上传巡逻点失败,巡逻点不能为空")
                    }
                }.show()
        }

        binding.addPatrolCommitBtn.setOnClickListener {
            pStart = binding.addPatrolStartTimeNowTv.text.toString()
            pEnd = binding.addPatrolEndTimeNowTv.text.toString()
            pTime = binding.addPatrolTimeNowTv.text.toString()
            pPoints = Gson().toJson(newPointList)

            if (pStart.isNotEmpty() && pEnd.isNotEmpty() && pTime.isNotEmpty() && pPoints.isNotEmpty()) {
                val map = mutableMapOf<String, String>()
                map[Const.PARAM_P_TIME] = pTime
                map[Const.PARAM_P_START] = pStart
                map[Const.PARAM_P_END] = pEnd
                map[Const.PARAM_P_POINTS] = pPoints

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                viewModel.addPatrol(body)
            } else {
                ToastUtils.showLong("不能有空选项")
            }
        }
    }
}